import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AttendanceService } from './attendance.service';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { In } from 'typeorm';
import { UserService } from 'src/user/user.service';
import * as moment from 'moment';
import { UseLog } from 'src/log/useLog.decorator';

@Controller('api/attendance')
@ApiTags("考勤")
@UseGuards(AuthGuard("jwt"))
export class AttendanceController {
    constructor(
        private readonly attendanceService: AttendanceService,
        private readonly userService: UserService,
    ) { }
    @Post("set")
    @UseLog("设置考勤信息")
    async set(
        @Body() { ids, createAt, ...rest },
        @CurrentUser() user: UserSys
    ) {
        const where = this.attendanceService.getUserWhere(user);
        where.id = In(ids);
        const users = await this.userService.userSys.find({ where });
        await this.attendanceService.attendance.delete({
            createAt: this.attendanceService.getBeteenDay(createAt),
            user: where
        })
        const entity = new Array(users.length).fill(0).map((_, i) => this.attendanceService.attendance.create({
            target: user,
            user: users[i],
            createAt,
            ...rest
        }));
        await this.attendanceService.attendance.save(entity);
    }

    @Get("getmine")
    @ApiOperation({ summary: "获取我的考勤" })
    getmine(
        @CurrentUser() user: UserSys,
        @Query("time") time: string
    ) {
        return this.attendanceService.attendance.find({
            where: {
                user: {
                    id: user.id
                },
                createAt: this.attendanceService.getBeteen(time || moment().format("YYYY-MM"))
            },
            relations: ["user", "target"]
        })
    }

    @Get("get")
    @ApiOperation({ summary: "获取考勤" })
    async get(
        @CurrentUser() user: UserSys,
        @Query("time") time: string
    ) {
        if (!time) time = moment().format("YYYY-MM")
        const where = this.attendanceService.getUserWhere(user);
        const users = await this.userService.userSys.find({ where, relations: ["system", "dept"] });
        const attendances = await this.attendanceService.attendance.find({
            where: {
                user: {
                    id: In(users.map(e => e.id))
                },
                createAt: this.attendanceService.getBeteen(time),
            },
            relations: ["user", "target"]
        })
        return {
            users,
            attendances
        }
    }

}
